{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# XOR Problem\n",
    "feedforward network or multilayer perceptron, MLP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = torch.tensor([0,0,0,1,1,0,1,1]).view(4,2).float()\n",
    "train_label = torch.tensor([0,1,1,0]).view(4,1).float()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Xor(nn.Module):\n",
    "    def __init__(self, is_init=False):\n",
    "        super().__init__()\n",
    "        self.hidden = nn.Linear(2,2)\n",
    "        self.output = nn.Linear(2,1, bias=False)\n",
    "        if is_init:\n",
    "            nn.init.uniform_(self.hidden.weight, -2, 2)\n",
    "            nn.init.uniform_(self.hidden.bias, -2, 2)\n",
    "            nn.init.uniform_(self.output.weight, -2, 2)\n",
    "    def forward(self, x):\n",
    "        x = F.relu(self.hidden(x))\n",
    "        x = self.output(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1000 loss 0.12947341799736023\n",
      "final loss 0.09983256459236145\n",
      "accuracy 1.0\n"
     ]
    }
   ],
   "source": [
    "xor = Xor()\n",
    "optimizer = optim.SGD(xor.parameters(), lr = 0.001, momentum=0.9)\n",
    "criterion = nn.MSELoss()\n",
    "epoch = 0\n",
    "while(True):\n",
    "    optimizer.zero_grad()\n",
    "    output = xor(train_data)\n",
    "    loss = criterion(output, train_label)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "    epoch += 1\n",
    "    if loss.item() <= 0.1:\n",
    "        break\n",
    "    if epoch % 1000 == 0:\n",
    "        print('epoch {} loss {}'.format(epoch, loss.item()))\n",
    "print('final loss',loss.item())\n",
    "predict = xor(train_data)\n",
    "accuracy = (torch.gt(predict,0.5).float()==train_label).sum().float()/4\n",
    "print('accuracy', accuracy.item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.0981],\n",
       "        [0.9466],\n",
       "        [0.5586],\n",
       "        [0.4374]], grad_fn=<MmBackward>)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Perfect xor model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "hidden_w = torch.tensor([1,1,1,1]).view(2,2)\n",
    "hidden_b = torch.tensor([0, -1]).view(2,1)\n",
    "output_w = torch.tensor([1, -2]).view(2,1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "hidden = torch.mm(train_data.float(), hidden_w.float()) + hidden_b.t().float()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.],\n",
       "        [1.],\n",
       "        [1.],\n",
       "        [0.]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output = torch.mm(F.relu(hidden), output_w.float())\n",
    "output"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
